package com.ymttest.business.service;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.ymatou.iapi.productmanager.parameter.*;
import com.ymatou.iapi.productsync.service.EsCall;
import com.ymatou.iapi.productsync.service.MongocrudCallOld;
import com.ymatou.iapi.sellerproduct.parameter.CatalogLevelBean;
import com.ymttest.common.order.userquery.util.HttpClientUtil;
import com.ymttest.database.annotation.SqlMapperFactory;
import com.ymttest.database.model.YmtActivity;
import com.ymttest.database.model.YmtProductActivityStock;
import com.ymttest.database.model.YmtProductPspInfo;
import com.ymttest.database.model.YmtSubCatalogs;
import com.ymttest.database.sqlwapper.*;
import com.ymttest.utils.MapUtil;
import com.ymttest.utils.YMTDateUtil;
import org.json.JSONArray;
import org.json.JSONObject;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

public class ProductManagerCallService {
	public static <T> T getBeanFromJson(JSONObject jsonObject, Class<T> clz){
		return  getBeanFromJson(jsonObject,clz,"yyyy-MM-dd HH:mm:ss");
	}
	
	public static <T> T getBeanFromJson(JSONObject jsonObject, Class<T> clz,String timeFormat){
		Gson gson = new GsonBuilder().setDateFormat(timeFormat).create();
		return  gson.fromJson(jsonObject.toString(), clz);
	}
	
	
	public static <T> T getBeanFromJson(JSONArray jsonArray, Class<T> clz){
		return  getBeanFromJson(jsonArray,clz,"yyyy-MM-dd HH:mm:ss");
	}
	
	public static <T> T getBeanFromJson(JSONArray jsonArray, Class<T> clz,String timeFormat){
		Gson gson = new GsonBuilder().setDateFormat(timeFormat).create();
		return  gson.fromJson(jsonArray.toString(), clz);
	}
	
	
	private static boolean changeObj2Bool(Object object) {
		try {
			if (object instanceof Boolean) {
				return (boolean) object;
			} else {
				int i = Integer.parseInt(object.toString());
				return i == 1 ? true : false;
			}
		} catch (Exception e) {
			return false;
		}
	}

	
	public static Object changeAsDefaultIfNull(Object object, Object defaultVal){
		if (object==null || object.toString().equalsIgnoreCase("null")){
			return defaultVal;
		}else{
			return object;
		}
	}
	
	public static boolean isPspSeller(int sellerId){
		String url = "http://selleraccount.iapi.ymatou.com/api/SellerAttribute/IsPSPSellerCheck";
		
		try {
			JSONObject ret = new JSONObject(HttpClientUtil.requestPost(url, MapUtil.hashMap("sellerId",String.valueOf(sellerId))));
			return ret.getJSONObject("Data").getBoolean("IsEnable");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return false;
	}
	
	
	
	public static void callMgoAndEs(int activityId,String productId,String actionType){
		new MongocrudCallOld().callAndGetReturnData(activityId, productId, actionType);
		new EsCall().callAndGetReturnData(activityId, productId, actionType);
	}
	
	
	
	public static ActivityTabProductCountDto getActivityTabProductCountDto(int sellerId,int liveId){
		ActivityTabProductCountDto atpcDto = new ActivityTabProductCountDto();
		List<Map<String,Object>> retInSql = SqlMapperFactory.getIntergratedProductMapper()
															.selectLiveProductTabCount(sellerId, liveId);
		
		atpcDto.setSoldoutCount(retInSql.stream().filter(x->((Integer)x.get("IsSoldout"))==0).mapToInt(y->Integer.parseInt(y.get("DataCount").toString())).sum());
		atpcDto.setSuspendCount(retInSql.stream().filter(x->((Integer)x.get("IsSoldout")==1) && ((Integer)x.get("iSellStatus"))==2).mapToInt(y->Integer.parseInt(y.get("DataCount").toString())).sum());
		atpcDto.setPutawayCount(retInSql.stream().filter(x->((Integer)x.get("IsSoldout")==1) && ((Integer)x.get("iSellStatus"))==1).mapToInt(y->Integer.parseInt(y.get("DataCount").toString())).sum());
		atpcDto.setReadyPutawayCount(retInSql.stream().filter(x->((Integer)x.get("IsSoldout")==1) && ((Integer)x.get("iSellStatus"))==0).mapToInt(y->Integer.parseInt(y.get("DataCount").toString())).sum());
		atpcDto.setTotalCount(atpcDto.getSoldoutCount()+atpcDto.getSuspendCount()+atpcDto.getPutawayCount()+atpcDto.getReadyPutawayCount());
		return atpcDto;
	}
	
	
	public static ProductCategoryListBean getProductCategoryListBean(int parentId) throws Exception{
		ProductCategoryListBean productCategoryListBean = new ProductCategoryListBean();
		List<ProductCategoryDto> categoryList = new ArrayList<>();
		
		@SuppressWarnings("rawtypes")
		List<Map> allCategoryList = new YmtProductCategoryWapper().getAllProductCategory();
		if (parentId!=-1){
			allCategoryList = allCategoryList.stream().filter(x->Integer.parseInt(x.get("iMasterCategory").toString())==parentId).collect(Collectors.toList());
		}
		
		
		for(int i=0;i<allCategoryList.size();i++){
			@SuppressWarnings("unchecked")
			Map<String,Object> ele = allCategoryList.get(i);
			ProductCategoryDto productCategoryDto = new ProductCategoryDto();
			productCategoryDto.setCategoryId(Integer.parseInt(ele.get("iCategoryId").toString()));
			productCategoryDto.setParentId(Integer.parseInt(ele.get("iMasterCategory").toString()));
			productCategoryDto.setCategoryName(ele.get("sCategory").toString());
			productCategoryDto.setLevel(Integer.parseInt(ele.get("iLevel").toString()));
			categoryList.add(productCategoryDto);
		}
		
	
		
		productCategoryListBean.setCategoryList(categoryList);
		return productCategoryListBean;
	}
	
	
	
	
	@SuppressWarnings("rawtypes")
	public static ProductCatalogListBean getProductCatalogListBean(String productId) throws Exception{
		ProductCatalogListBean productCatalogListBean = new ProductCatalogListBean();
		List<ProductCatalogDto> catalogList = new ArrayList<>();
		
		
		//Map productInSql = new YmtProductsIWapper().selectProductByProductIdforMap(productId).get(0);
		List<Map> catalogsInSqlList = new YmtCatalogsIWapper().selectCatalogsByProductIdforMap(productId);

		catalogsInSqlList.forEach(catalogInSql->{
			System.out.println("sql="+catalogInSql);
			String catalogId = catalogInSql.get("sCatalogId").toString();
			ProductCatalogDto productCatalogDto = new ProductCatalogDto();
			productCatalogDto.setProductId(catalogInSql.get("sProductId").toString());
			productCatalogDto.setCatalogId(catalogId);
			productCatalogDto.setSellerId(Integer.parseInt(catalogInSql.get("iUserId").toString()));
			productCatalogDto.setPrice(Double.parseDouble(catalogInSql.get("fQuotePrice").toString()));
			productCatalogDto.setNewPrice(Double.parseDouble(catalogInSql.get("fNewCustomerPrice").toString()));
			productCatalogDto.setVipPrice(Double.parseDouble(catalogInSql.get("fVipPrice").toString()));
			productCatalogDto.setStockNum(Integer.parseInt(catalogInSql.get("iNum").toString()));
			productCatalogDto.setSku(catalogInSql.get("sSKU")==null?null:catalogInSql.get("sSKU").toString());
			productCatalogDto.setAddTime((Date)catalogInSql.get("dAddTime"));
			productCatalogDto.setProductCode(catalogInSql.get("sProductCode")==null?null:catalogInSql.get("sProductCode").toString());
			productCatalogDto.setExtDeliveryType(Integer.parseInt(catalogInSql.get("iMultiLogistics").toString()));
			productCatalogDto.setAction(Integer.parseInt(catalogInSql.get("iAction").toString()));
			productCatalogDto.setWeight(Double.parseDouble(catalogInSql.get("Weight").toString()));
			productCatalogDto.setPackage(changeObj2Bool(catalogInSql.get("IsPackage")));
			productCatalogDto.setPreSale(changeObj2Bool(catalogInSql.get("IsPreSale")));
			productCatalogDto.setSaleCommission(new BigDecimal(catalogInSql.get("SaleCommission").toString()));
			if (catalogInSql.get("SaleCommissions")!=null){
				String[] saleCommissions = catalogInSql.get("SaleCommissions").toString().split(",");
				productCatalogDto.setSaleCommissionList(Arrays.asList(new BigDecimal(saleCommissions[0]).setScale(2),new BigDecimal(saleCommissions[1]).setScale(2),new BigDecimal(saleCommissions[2]).setScale(2)));
			}
			try {
				List<Map> catalogPropertyList = new YmtCatalogsIWapper().selectCatalogPropsByCatalogId(catalogId);
				if (catalogPropertyList.size()>0){
					List<CatalogPropertyDto> propertyList = new ArrayList<>();
					catalogPropertyList.forEach(catalogPropertyInSql->{
						CatalogPropertyDto catalogPropertyDto = new CatalogPropertyDto();
						catalogPropertyDto.setName(catalogPropertyInSql.get("sProductProperty").toString());
						catalogPropertyDto.setValue(catalogPropertyInSql.get("sCategoryAttribute").toString());
						catalogPropertyDto.setPic(catalogPropertyInSql.get("sPicUrl").toString());
						propertyList.add(catalogPropertyDto);
					});
					productCatalogDto.setPropertyList(propertyList);
				}
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			
			//套餐
			try {
				List<YmtSubCatalogs> ymtSubCatalogsList = new YmtSubCatalogsWapper().selectListByCatalogId(catalogId);
				if (ymtSubCatalogsList.size()>0){
					List<CatalogPackageDto> packageList = new ArrayList<>();
					ymtSubCatalogsList.forEach(subCatalogInSql->{
						try {
						CatalogPackageDto catalogPackageDto = new CatalogPackageDto();
						catalogPackageDto.setCatalogId(catalogId);
						catalogPackageDto.setSubCatalogId(subCatalogInSql.getSubCatalogId());
						catalogPackageDto.setSubCatalogName(subCatalogInSql.getSubCatalogName());
						catalogPackageDto.setPrice(subCatalogInSql.getPrice().doubleValue());
						catalogPackageDto.setNum(subCatalogInSql.getNum());
						catalogPackageDto.setSku(subCatalogInSql.getSku());
						catalogPackageDto.setProductCode(subCatalogInSql.getProductCode());
						
						CatalogLevelBean catalogLevelBean = SellerProductCallService.getProductCategroyByThirdCategoryId(subCatalogInSql.getThirdCategoryId());
						catalogPackageDto.setMasterCategoryId(catalogLevelBean.getMasterCategoryId());
						catalogPackageDto.setMasterCategoryName(catalogLevelBean.getMasterCategoryName());
						catalogPackageDto.setSecondCategoryId(catalogLevelBean.getSecondCategoryId());
						catalogPackageDto.setSecondCategoryName(catalogLevelBean.getSecondCategoryName());
						catalogPackageDto.setThirdCategoryId(catalogLevelBean.getThirdCategoryId());
						catalogPackageDto.setThirdCategoryName(catalogLevelBean.getThirdCategoryName());
						
						packageList.add(catalogPackageDto);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					});
					productCatalogDto.setPackageList(packageList);
				}
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			catalogList.add(productCatalogDto);
		});
		
		
		productCatalogListBean.setProductCatalogInfos(catalogList);
		return productCatalogListBean;
	}
	
	
	/**
	 * 增加了新的字段，新的佣金比例
	 * @param productId
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("rawtypes")
	public static ProductCatalogListBean getProductCatalogListBeanV2(String productId) throws Exception{
		ProductCatalogListBean productCatalogListBean = new ProductCatalogListBean();
		List<ProductCatalogDto> catalogList = new ArrayList<>();
		
		
		//Map productInSql = new YmtProductsIWapper().selectProductByProductIdforMap(productId).get(0);
		List<Map> catalogsInSqlList = new YmtCatalogsIWapper().selectCatalogsByProductIdforMap(productId);

		catalogsInSqlList.forEach(catalogInSql->{
			System.out.println("sql="+catalogInSql);
			String catalogId = catalogInSql.get("sCatalogId").toString();
			ProductCatalogDto productCatalogDto = new ProductCatalogDto();
			productCatalogDto.setProductId(catalogInSql.get("sProductId").toString());
			productCatalogDto.setCatalogId(catalogId);
			productCatalogDto.setSellerId(Integer.parseInt(catalogInSql.get("iUserId").toString()));
			productCatalogDto.setPrice(Double.parseDouble(catalogInSql.get("fQuotePrice").toString()));
			productCatalogDto.setNewPrice(Double.parseDouble(catalogInSql.get("fNewCustomerPrice").toString()));
			productCatalogDto.setVipPrice(Double.parseDouble(catalogInSql.get("fVipPrice").toString()));
			productCatalogDto.setStockNum(Integer.parseInt(catalogInSql.get("iNum").toString()));
			productCatalogDto.setSku(catalogInSql.get("sSKU")==null?null:catalogInSql.get("sSKU").toString());
			productCatalogDto.setAddTime((Date)catalogInSql.get("dAddTime"));
			productCatalogDto.setProductCode(catalogInSql.get("sProductCode")==null?null:catalogInSql.get("sProductCode").toString());
			productCatalogDto.setExtDeliveryType(Integer.parseInt(catalogInSql.get("iMultiLogistics").toString()));
			productCatalogDto.setAction(Integer.parseInt(catalogInSql.get("iAction").toString()));
			productCatalogDto.setWeight(Double.parseDouble(catalogInSql.get("Weight").toString()));
			productCatalogDto.setPackage(changeObj2Bool(catalogInSql.get("IsPackage")));
			productCatalogDto.setPreSale(changeObj2Bool(catalogInSql.get("IsPreSale")));
			
			productCatalogDto.setSaleCommission(new BigDecimal(catalogInSql.get("SaleCommission").toString()));
			
//			productCatalogDto.setSaleCommission(catalogInSql.get("SaleCommission")==null||catalogInSql.get("SaleCommission").toString().equals("0.00")?null:new BigDecimal(catalogInSql.get("SaleCommission").toString()));
			if (catalogInSql.get("SaleCommissions")!=null){
				String[] saleCommissions = catalogInSql.get("SaleCommissions").toString().split(",");
				productCatalogDto.setSaleCommissionList(Arrays.asList(new BigDecimal(saleCommissions[0]).setScale(2),new BigDecimal(saleCommissions[1]).setScale(2),new BigDecimal(saleCommissions[2]).setScale(2),new BigDecimal(saleCommissions[3]).setScale(2)));
			}
			if (catalogInSql.get("SaleCommissionPercent")!=null){
				String[] saleCommissions = catalogInSql.get("SaleCommissionPercent").toString().split(",");
				if(saleCommissions.length!=1){
					productCatalogDto.setSaleCommissionList(Arrays.asList(new BigDecimal(saleCommissions[0]).setScale(2),new BigDecimal(saleCommissions[1]).setScale(2),new BigDecimal(saleCommissions[2]).setScale(2),new BigDecimal(saleCommissions[3]).setScale(2)));
				}else {
					productCatalogDto.setSaleCommission(new BigDecimal(saleCommissions[0]).setScale(2));
				}
			}
			
			try {
				List<Map> catalogPropertyList = new YmtCatalogsIWapper().selectCatalogPropsByCatalogId(catalogId);
				if (catalogPropertyList.size()>0){
					List<CatalogPropertyDto> propertyList = new ArrayList<>();
					catalogPropertyList.forEach(catalogPropertyInSql->{
						CatalogPropertyDto catalogPropertyDto = new CatalogPropertyDto();
						catalogPropertyDto.setName(catalogPropertyInSql.get("sProductProperty").toString());
						catalogPropertyDto.setValue(catalogPropertyInSql.get("sCategoryAttribute").toString());
						catalogPropertyDto.setPic(catalogPropertyInSql.get("sPicUrl").toString());
						propertyList.add(catalogPropertyDto);
					});
					productCatalogDto.setPropertyList(propertyList);
				}
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			
			//套餐
			try {
				List<YmtSubCatalogs> ymtSubCatalogsList = new YmtSubCatalogsWapper().selectListByCatalogId(catalogId);
				if (ymtSubCatalogsList.size()>0){
					List<CatalogPackageDto> packageList = new ArrayList<>();
					ymtSubCatalogsList.forEach(subCatalogInSql->{
						try {
						CatalogPackageDto catalogPackageDto = new CatalogPackageDto();
						catalogPackageDto.setCatalogId(catalogId);
						catalogPackageDto.setSubCatalogId(subCatalogInSql.getSubCatalogId());
						catalogPackageDto.setSubCatalogName(subCatalogInSql.getSubCatalogName());
						catalogPackageDto.setPrice(subCatalogInSql.getPrice().doubleValue());
						catalogPackageDto.setNum(subCatalogInSql.getNum());
						catalogPackageDto.setSku(subCatalogInSql.getSku());
						catalogPackageDto.setProductCode(subCatalogInSql.getProductCode());
						
						CatalogLevelBean catalogLevelBean = SellerProductCallService.getProductCategroyByThirdCategoryId(subCatalogInSql.getThirdCategoryId());
						catalogPackageDto.setMasterCategoryId(catalogLevelBean.getMasterCategoryId());
						catalogPackageDto.setMasterCategoryName(catalogLevelBean.getMasterCategoryName());
						catalogPackageDto.setSecondCategoryId(catalogLevelBean.getSecondCategoryId());
						catalogPackageDto.setSecondCategoryName(catalogLevelBean.getSecondCategoryName());
						catalogPackageDto.setThirdCategoryId(catalogLevelBean.getThirdCategoryId());
						catalogPackageDto.setThirdCategoryName(catalogLevelBean.getThirdCategoryName());
						
						packageList.add(catalogPackageDto);
						} catch (InterruptedException e) {
							e.printStackTrace();
						}
					});
					productCatalogDto.setPackageList(packageList);
				}
				
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
			
			catalogList.add(productCatalogDto);
		});
		
		
		productCatalogListBean.setProductCatalogInfos(catalogList);
		return productCatalogListBean;
	}
	

	@SuppressWarnings({ "unchecked", "rawtypes" })
	public static QuerySellerProductListResponseBean getQuerySellerProductListResponseBean(List<String> tgtProductList) throws Exception{
		QuerySellerProductListResponseBean querySellerProductListResponseBean = new QuerySellerProductListResponseBean();
		List<ProductInListDtoBean> productDtoList = new ArrayList<>();
		
		YmtProductsIWapper ymtProductsIWapper = new YmtProductsIWapper();
		YmtCatalogsIWapper ymtCatalogsIWapper = new YmtCatalogsIWapper();
		YmtProductsInLiveWapper ymtProductsInLiveWapper = new YmtProductsInLiveWapper();
		YmtProductActivityStockWapper ymtProductActivityStockWapper = new YmtProductActivityStockWapper();
		YmtProductPspInfoWapper ymtProductPspInfoWapper = new YmtProductPspInfoWapper();
		
		for(int i=0;i<tgtProductList.size();i++){
			String productId = tgtProductList.get(i);
			//sql取数据
			Map<String,Object> productInSql = ymtProductsIWapper.selectProductByProductIdforMap(productId).get(0);
			List<Map> catalogsInSql = ymtCatalogsIWapper.selectCatalogsByProductIdforMap(productId);
			List<Map> livesInSql = ymtProductsInLiveWapper.selectInLiveByProductId(productId).stream().filter(x->((Date)x.get("dEndTime")).after(YMTDateUtil.getDate())).collect(Collectors.toList());
			List<YmtProductActivityStock> activitysInSql = ymtProductActivityStockWapper.selectByProductId(productId).stream()
															.filter(x->x.getDendtime().after(YMTDateUtil.getDate())&&x.getIstocknum()>=0&&x.getDendtime().after(x.getDbegintime()))
															.collect(Collectors.toList());
			List<YmtProductPspInfo> ymtProductPspInfoList = ymtProductPspInfoWapper.selectByProductId(productId);
			//组装数据
			ProductInListDtoBean productInListDtoBean = new ProductInListDtoBean();
			productInListDtoBean.setProductId(productId);
			productInListDtoBean.setProductName(productInSql.get("sProduct").toString());
			productInListDtoBean.setMainPicUrl(productInSql.get("sPicUrl").toString());
			//add by summing 20201225
			productInListDtoBean.setBrandId(Integer.parseInt(productInSql.get("iBrandId").toString()));
			productInListDtoBean.setBrandName(productInSql.get("sBrand").toString());
			productInListDtoBean.setSecondCategoryId(Integer.parseInt(productInSql.get("iCategoryId").toString()));
			productInListDtoBean.setThirdCategoryId(Integer.parseInt(productInSql.get("iThirdCategoryId").toString()));
			productInListDtoBean.setMinCatalogPrice(Collections.min(catalogsInSql.
																	stream().map(x->Double.parseDouble(x.get("fQuotePrice").toString()))
																	.collect(Collectors.toList())));
			
			productInListDtoBean.setMaxCatalogPrice(Collections.max(catalogsInSql.
					stream().map(x->Double.parseDouble(x.get("fQuotePrice").toString()))
					.collect(Collectors.toList())));
			
			productInListDtoBean.setHasNewCustomerPrice(catalogsInSql.stream().map(x->Double.parseDouble(x.get("fNewCustomerPrice").toString())).anyMatch(y->y>0));
			productInListDtoBean.setHasVipPrice(catalogsInSql.stream().map(x->Double.parseDouble(x.get("fVipPrice").toString())).anyMatch(y->y>0));
			
			List templateProduct =  ymtProductsIWapper.getProductDeliveryTemplateByProdId(productId).stream()
													.filter(x->Integer.parseInt(x.get("Status").toString())==1).collect(Collectors.toList());
			productInListDtoBean.setIsFreeShipping(templateProduct.size()==0);
			
			
			
			productInListDtoBean.setIsFreeTariff(Integer.parseInt(productInSql.get("iTariffType").toString())==0);
			productInListDtoBean.setHasCatalogs(catalogsInSql.size()>0);
			productInListDtoBean.setCatalogStatus(Integer.parseInt(productInSql.get("iCatalogStatus").toString()));
			productInListDtoBean.setCatalogType(Integer.parseInt(productInSql.get("iCatalogType").toString()));
			productInListDtoBean.setProductStock(catalogsInSql.stream().map(x->Integer.parseInt(x.get("iNum").toString())).collect(Collectors.summingInt(Integer::intValue)));
			productInListDtoBean.setValidStart((Date)productInSql.get("validStart"));
			productInListDtoBean.setValidEnd((Date)productInSql.get("validEnd"));
			productInListDtoBean.setAddTime((Date)productInSql.get("dAddTime"));
			productInListDtoBean.setSaleKindList(getProductSaleKindList(productInSql,livesInSql,activitysInSql));
			productInListDtoBean.setLiveIdList(livesInSql.stream().map(x->Integer.parseInt(x.get("iActivityId").toString())).collect(Collectors.toList()));
			
			Date now = YMTDateUtil.getDateBeforeOrNextSecond(300);
			Map startLive = livesInSql.stream().filter(c->Integer.parseInt(c.get("iSellStatus").toString())==1&&((Date)c.get("dStartTime")).before(now)&&((Date)c.get("dEndTime")).after(now)).findAny().orElse(null);
			if (startLive!=null){
				productInListDtoBean.setValidLiveId(Integer.parseInt(startLive.get("iActivityId").toString()));
			}
			
			
			
			productInListDtoBean.setIsPspProduct(Boolean.parseBoolean(productInSql.get("IsPspProduct").toString()));
			productInListDtoBean.setMultiLogistics(Integer.parseInt(productInSql.get("iMultiLogistics").toString()));
			productInListDtoBean.setFlightBalance(Double.parseDouble(productInSql.get("dFlightBalance").toString()));
			productInListDtoBean.setCheckStatus(Integer.parseInt(productInSql.get("CheckStatus").toString()));
			
			
			List<ProductActivityBean> productActivityList = new ArrayList<>();
			if (activitysInSql.size()>0){
				Map<Integer,List<YmtProductActivityStock>> activityIdAndActivityProductMap = activitysInSql.stream().collect(Collectors.groupingBy(YmtProductActivityStock::getIactivityid));
				
				activityIdAndActivityProductMap.forEach((aid,aidProd)->{
					ProductActivityBean productActivityBean = new ProductActivityBean();
					
					int allStock = aidProd.stream().map(x->x.getIstocknum()).collect(Collectors.summingInt(Integer::intValue));
					try {
						YmtActivity ymtActivity = new YmtActivityWapper().getRecordByActivityId(aid);
						productActivityBean.setActivityId(aid);
						productActivityBean.setActivityName(ymtActivity.getSname());
						productActivityBean.setBeginTime(ymtActivity.getDbegintime());
						productActivityBean.setEndTime(ymtActivity.getDendtime());
						productActivityBean.setStockNum(allStock);
						productActivityList.add(productActivityBean);
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
					
 				});
				
			}
			productInListDtoBean.setProductActivityList(productActivityList);
			
			
			if (ymtProductPspInfoList.size()>0){
				productInListDtoBean.setPspStatus(isPspSeller((int)productInSql.get("iUserId"))?ymtProductPspInfoList.get(0).getPspStatus():0);
			}
			
			productInListDtoBean.setListingTime((Date)productInSql.get("dListingTime"));
			productInListDtoBean.setNewEndtime((Date)productInSql.get("dNewEndtime"));
			productInListDtoBean.setIsNew(Boolean.parseBoolean(productInSql.get("isNew").toString()));

			if (!(productInListDtoBean.getListingTime().before(YMTDateUtil.getDate()) && productInListDtoBean.getNewEndtime().after(YMTDateUtil.getDate()))){
				productInListDtoBean.setIsNew(false);
			}
			
			//测试环境去掉巡检相关--- 目前开启巡检会导致数据库过慢 20190528
//			List<String> tips = SellerProductCallService.getProductViolateTips(productId);
//			if (tips.size()>0){
//				productInListDtoBean.setViolateTips(tips);
//			}else{
			productInListDtoBean.setViolateTips(new ArrayList<>());
//			}
			
			productInListDtoBean.setIsPreSale(catalogsInSql.stream().anyMatch(x->changeObj2Bool(x.get("IsPreSale"))));
			
		
			
			 List<Double> newPriceList = catalogsInSql.stream().filter(c->Double.parseDouble(c.get("fNewCustomerPrice").toString())>0)
								  .map(x->Double.parseDouble(x.get("fNewCustomerPrice").toString()))
								  .collect(Collectors.toList());
			 if (newPriceList != null && newPriceList.size() > 0){
				 productInListDtoBean.setNewGuestPrice(Collections.min(newPriceList));
			 }
			
			
			 List<Double> vipPriceList = catalogsInSql.stream().filter(c->Double.parseDouble(c.get("fVipPrice").toString())>0)
					  .map(x->Double.parseDouble(x.get("fVipPrice").toString()))
					  .collect(Collectors.toList());
			if (vipPriceList != null && vipPriceList.size() > 0){
				 productInListDtoBean.setVipPrice(Collections.min(vipPriceList));
			}
						 
			productInListDtoBean.setCatalogStatusText(getDeliveryTypeText(Integer.parseInt(productInSql.get("iCatalogStatus").toString()),
					Integer.parseInt(productInSql.get("iMultiLogistics").toString())));

		
			CatalogLevelBean catalogLevelBean = SellerProductCallService.getProductCategroyByThirdCategoryId(Integer.parseInt(productInSql.get("iThirdCategoryId").toString()));
			productInListDtoBean.setCategoryName(catalogLevelBean.getMasterCategoryName()+"/"+catalogLevelBean.getSecondCategoryName()+"/"+catalogLevelBean.getThirdCategoryName());
			
			//todo
			productInListDtoBean.setSellNum(0);
			productInListDtoBean.setStatusList(getProductStatusList(productInSql,
					catalogsInSql,livesInSql,activitysInSql));
			
			productDtoList.add(productInListDtoBean);
		}
				
		querySellerProductListResponseBean.setProductList(productDtoList);
		querySellerProductListResponseBean.setTotals(tgtProductList.size());
		return querySellerProductListResponseBean;
	}
	
	
	
	 private static String getDeliveryTypeText(int catalogStatus, int multiLogistics) {
	        String result = "";
	        switch (catalogStatus) {
	            // todo: 1= trade
	            case 2:
	                result = "第三方直邮";
	                break;
	            case 3:
	                result = "贝海直邮";
	                break;
	            case 4:
	                result = "第三方保税";
	                break;
	            case 5:
	                result = "贝海保税";
	                break;
	            case 6:
	                result = "认证直邮";
	                break;
	            case 7:
	                result = "拼邮";
	                break;
	            default:
	                // todo: exception log
	                break;
	        }

	        if (multiLogistics == 3) result += ", 贝海直邮";
	        return result;
	    }
	
	 private static List<Integer> getProductStatusList(Map<String,Object> productInSql, List<Map> catalogsInSql,List<Map> livesInSql, List<YmtProductActivityStock> activitysInSql) {
		 List<Integer> statusList = new ArrayList<>();
		 Date now = YMTDateUtil.getDateBeforeOrNextSecond(300);

        // 是否有进行中的直播，并且商品在直播中上架(sellStatus == 1)
		 boolean validInLive = false;
		if (livesInSql.size()>0){
	        List startLive = livesInSql.stream().filter(c->Integer.parseInt(c.get("iSellStatus").toString())==1&&((Date)c.get("dStartTime")).before(now)&&((Date)c.get("dEndTime")).after(now)).collect(Collectors.toList());
	         validInLive = (startLive.size()>0);
		}
        
        int sumStock = catalogsInSql.stream().map(x->Integer.parseInt(x.get("iNum").toString())).collect(Collectors.summingInt(Integer::intValue));
        
        if (sumStock==0){
        	statusList.add(3);
        }else{
        	 boolean onShelf = (((Date)productInSql.get("validStart")).before(now)&& ((Date)productInSql.get("validEnd")).after(now) || validInLive || activitysInSql.size()>0 );
        	 if (onShelf){
        		 statusList.add(1);
        	 }else{
        		 statusList.add(2);
        	 }
        		 
        }
        
        
        
        return statusList;
	 }
	
	 @SuppressWarnings("rawtypes")
	private static List<Integer> getProductSaleKindList(Map<String,Object> productInSql, List<Map> livesInSql, List<YmtProductActivityStock> activitysInSql) {
		List<Integer> saleKindList = new ArrayList<>();
		Date now = YMTDateUtil.getDateBeforeOrNextSecond(300);
		
		if (((Date)productInSql.get("validStart")).before(now)  && ((Date)productInSql.get("validEnd")).after(now)) {
			saleKindList.add(1);
		}
		
		if (livesInSql.size()>0){
			List startLive = livesInSql.stream().filter(c->Integer.parseInt(c.get("iSellStatus").toString())==1&&((Date)c.get("dStartTime")).before(now)&&((Date)c.get("dEndTime")).after(now)).collect(Collectors.toList());
			if (startLive.size()>0){
				saleKindList.add(2);
			}
		}
		
		
		if (activitysInSql.size()>0){
			saleKindList.add(3);
		}
		
		return saleKindList;
	}
	
	
	
	
	
}
